package com.hunttown.mes.manage.service.files;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;

/**
 * @title: 文件上传
 * @author: wangjunfu
 * @date: 2022年11月29日 10:53
 * @description:
 */
@Service
public class FileSystemStorageManageService {

    /**
     * 存储到本地
     *
     * @param file         文件
     * @param filename     文件名（请传唯一key，不要传中文）
     * @param absolutePath 根路径（请事先创建）
     * @return 返回文件名
     */
    public String store(MultipartFile file, String filename, String absolutePath) {
        if (filename == null || filename.isEmpty()) {
            filename = StringUtils.cleanPath(file.getOriginalFilename());
        }

        try {
            filename = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
        } catch (UnsupportedEncodingException e1) {
            System.out.println("fail to URLEncoder.encode utf8 for: " + filename);
        }

        try {
            if (file.isEmpty()) {
                throw new StorageException("Failed to store empty file " + filename);
            }

            if (filename.contains("..")) {
                throw new StorageException("Cannot store file with relative path outside current directory " + filename);
            }

            Path rootLocation = getPath(absolutePath);
            Files.copy(file.getInputStream(), rootLocation.resolve(filename), StandardCopyOption.REPLACE_EXISTING);

            return filename;

        } catch (IOException e) {
            throw new StorageException("Failed to store file " + filename, e);
        }
    }

    //读取文件
    public Resource loadAsResource(String filename, String absolutePath) {
        try {
            Path rootLocation = getPath(absolutePath);
            Path file = load(rootLocation, filename);

            UrlResource urlResource = new UrlResource(file.toUri());

            if (urlResource.exists() || urlResource.isReadable()) {
                return (Resource) urlResource;
            }

            if (!urlResource.exists()) {
                throw new StorageFileNotFoundException("file UrlResource not exists: " + urlResource.getFilename());
            }

            throw new StorageFileNotFoundException("file UrlResource not readable: " + urlResource.getFilename());

        } catch (MalformedURLException e) {
            throw new StorageFileNotFoundException("the given URL path is not valid: " + filename, e);
        }
    }

    //获取文件路径（如果不存在则创建）
    private Path getPath(String absolutePath) {
        return Paths.get(absolutePath);
    }

    //文件路径
    private Path load(Path rootLocation, String filename) {
        return rootLocation.resolve(filename);
    }
}
